<template>
    <div class="health-record-container">
        <div class="header">
            <!-- 新增用户ID输入框 -->
            <div class="user-id-input" v-if="isDoctor">
                <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable style="width: 200px"
                    @change="handleSearch">
                    <template #prepend>用户ID</template>
                </el-input>
            </div>

            <div class="search">
                <el-date-picker v-model="searchForm.startDate" type="date" placeholder="开始日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" @change="handleSearch" />
                <el-date-picker v-model="searchForm.endDate" type="date" placeholder="结束日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" @change="handleSearch" />
            </div>
            <el-button type="success" @click="handleAdd">新增记录</el-button>
        </div>

        <el-table :data="tableData" border style="width: 100%" height="450">
            <el-table-column prop="recordId" label="记录ID" width="80" />
            <el-table-column prop="steps" label="步数" width="120" />
            <el-table-column prop="sleepDuration" label="睡眠时长(小时)" width="140" />
            <el-table-column prop="waterIntake" label="饮水量(ml)" width="140" />
            <el-table-column label="记录日期" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.recordDate) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
            <el-form :model="form" label-width="100px">
                <el-form-item label="步数">
                    <el-input-number v-model="form.steps" :min="0" />
                </el-form-item>
                <el-form-item label="睡眠时长(小时)">
                    <el-input-number v-model="form.sleepDuration" :min="0" :precision="1" />
                </el-form-item>
                <el-form-item label="饮水量(ml)">
                    <el-input-number v-model="form.waterIntake" :min="0" />
                </el-form-item>
                <el-form-item label="记录日期">
                    <el-date-picker v-model="form.recordDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
    queryHealthRecord,
    updateHealthRecord,
    deleteHealthRecord,
    addHealthRecord
} from '@/api/record';

// 表格数据
const tableData = ref([]);
const isDoctor = localStorage.getItem('role') === 'doctor' || localStorage.getItem('role') === 'admin'; // 检查角色是否为医生或管理员;


// 修改加载数据方法
const loadHealthRecords = async (params) => {
    try {
        // 医生角色输入验证
        if (isDoctor.value && !isValidUserId.value) {
            ElMessage.error('请输入有效的数字用户ID');
            return;
        }

        // 自动设置用户ID逻辑
        let userId = '';
        if (localStorage.getItem('role') === 'patient') {
            userId = localStorage.getItem('id');
            searchForm.value.userId = userId; // 自动填充当前患者ID
        } else {
            userId = searchForm.value.userId;
        }

        // 转换为数字验证
        const numericUserId = parseInt(userId);
        if (isNaN(numericUserId)) {
            ElMessage.error('用户ID必须为有效数字');
            return;
        }

        const requestParams = {
            userId: numericUserId,
            startDate: params?.startDate || "2000-01-01",
            endDate: params?.endDate || "3000-01-01",
            pageIndex: 1,
            pageSize: 5
        };

        console.log('请求参数:', requestParams); // 调试日志

        const response = await queryHealthRecord(requestParams);
        console.log('响应数据:', response); // 调试日志

        if (response.code === '000') {
            tableData.value = response.data?.records || [];
            localStorage.setItem('aimid', numericUserId); // 存储用户ID到本地存储
            if (tableData.value.length === 0) {
                ElMessage.warning('未查询到相关记录');
            }
        } else {
            ElMessage.error(`获取健康记录失败: ${response.msg}`);
        }
    } catch (error) {
        ElMessage.error(`请求异常: ${error.message}`);
    }
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 日期范围查询
// 修改搜索表单结构
const searchForm = ref({
    userId: '', // 新增用户ID字段
    startDate: "2020-01-01",
    endDate: "2025-05-31"
});

const handleSearch = () => {
    loadHealthRecords(searchForm.value);
};

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增健康记录');
const form = ref({
    recordId: 0,
    userId: localStorage.getItem('id'),
    steps: 0,
    sleepDuration: 0,
    waterIntake: 0,
    recordDate: ''
});

// 修改新增记录方法
const handleAdd = () => {
    // 设置默认用户ID
    let defaultUserId = '';
    if (localStorage.getItem('role') === 'patient') {
        defaultUserId = localStorage.getItem('id');
    } else {
        defaultUserId = searchForm.value.userId;
    }

    form.value = {
        recordId: 0,
        userId: defaultUserId,
        steps: 0,
        sleepDuration: 0,
        waterIntake: 0,
        recordDate: new Date().toISOString().slice(0, 10)
    };
    dialogTitle.value = '新增健康记录';
    dialogVisible.value = true;
};


// 打开编辑对话框
const handleUpdate = (row) => {
    form.value = {
        recordId: row.recordId,
        userId: row.userId,
        steps: row.steps,
        sleepDuration: row.sleepDuration,
        waterIntake: row.waterIntake,
        recordDate: formatDate(row.recordDate)
    };
    dialogTitle.value = '编辑健康记录';
    dialogVisible.value = true;
};

// 确认提交（新增或编辑）
const confirmSubmit = async () => {
    try {
        if (dialogTitle.value === '新增健康记录') {
            // 新增记录
            const addParams = {
                userId: parseInt(form.value.userId),
                steps: form.value.steps,
                sleepDuration: form.value.sleepDuration,
                waterIntake: form.value.waterIntake,
                recordDate: form.value.recordDate
            };

            const response = await addHealthRecord(addParams);

            if (response.code === '000') {
                ElMessage.success('新增成功');
                dialogVisible.value = false;
                loadHealthRecords(searchForm.value); // 刷新数据
            } else {
                ElMessage.error(`新增失败: ${response.msg}`);
            }
        } else {
            // 编辑记录
            const updateParams = {
                recordId: form.value.recordId,
                userId: form.value.userId,
                steps: form.value.steps,
                sleepDuration: form.value.sleepDuration,
                waterIntake: form.value.waterIntake
            };

            const response = await updateHealthRecord(updateParams);

            if (response.code === '000') {
                ElMessage.success('更新成功');
                dialogVisible.value = false;
                loadHealthRecords(searchForm.value); // 刷新数据
            } else {
                ElMessage.error(`更新失败: ${response.msg}`);
            }
        }
    } catch (error) {
        ElMessage.error(`操作时出错: ${error.message}`);
    }
};

// 处理删除
const handleDelete = async (row) => {
    try {
        const confirm = await ElMessageBox.confirm(
            '确定要删除这条健康记录吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        if (confirm === 'confirm') {
            const params = { recordId: row.recordId };
            const response = await deleteHealthRecord(params);

            if (response.code === '000') {
                ElMessage.success('删除成功');
                loadHealthRecords(searchForm.value); // 刷新数据
            } else {
                ElMessage.error(`删除失败: ${response.msg}`);
            }
        }
    } catch (error) {
        // 用户取消删除或发生错误
        if (error !== 'cancel') {
            ElMessage.error(`删除时出错: ${error.message}`);
        }
    }
};

// 页面加载时获取数据
onMounted(() => {
    // 自动设置初始用户ID
    if (localStorage.getItem('role') === 'patient') {
        searchForm.value.userId = localStorage.getItem('id');
    }
    loadHealthRecords();
});
</script>

<style scoped>
.health-record-container {
    padding: 20px;
    background-color: #f5f7fa;
}

.header {
    margin-bottom: 12px;
    /* 减少底部间距 */
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;
    /* 添加元素间距控制 */
}

.search {
    display: flex;
    gap: 8px;
    /* 缩小日期选择器间距 */
    align-items: center;
}

/* 优化表格间距 */
.el-table {
    --el-table-cell-padding:
        /* 单元格内边距 */
        --el-table-header-cell-padding: 10px 15px;
    margin-top: 20px;
    /* 减少顶部间距 */
}

/* 对话框表单紧凑布局 */
.el-form {
    .el-form-item {
        margin-bottom: 25px;
        /* 减少表单项间距 */

        :deep(.el-form-item__label) {
            padding-right: 15px;
            /* 标签右侧间距 */
        }

        :deep(.el-form-item__content) {
            flex: 1;
        }
    }
}

/* 按钮紧凑布局 */
.el-button {
    +.el-button {
        margin-left: 6px;
        /* 缩小按钮间距 */
    }
}

/* 日期选择器紧凑样式 */
.el-date-editor {
    --el-date-editor-width: 180px;
    /* 固定宽度 */

    &.el-range-editor {
        --el-date-range-width: 260px;
    }
}

/* 操作列按钮紧凑 */
.el-table__cell .cell {
    .el-button {
        padding: 6px 8px;

        &+.el-button {
            margin-left: 4px;
        }
    }
}
</style>